<template>
	<wd-navbar title="个人中心" @click-left="onBack" custom-style="background-color: transparent !important;" leftArrow safeAreaInsetTop fixed></wd-navbar>
	<view class="head-bg"></view>
	<view class="page-content">
		<!-- 基本信息 -->
		<view v-if="userInfo" class="user-info">
			<wd-img style="border: 1px solid #eee" width="120rpx" height="120rpx" :src="utils.getAvatarPath(userInfo.avatar)" round />
			<view class="right-wrap">
				<view class="nickname">{{ userInfo.nickname || '未知用户' }}</view>
				<view class="id">ID:{{ userInfo.sn || '---' }}</view>
				<view class="intro">{{ userInfo.introduction || '这人很懒，没有留下什么...' }}</view>
			</view>
			<!-- 关注按钮 -->
			<view v-if="currentUserId !== userInfo?.id" class="follow-btn-wrap">
				<wd-button :type="isFollowing || isMutualFollowing ? 'default' : 'info'" size="small" :class="{ followed: isFollowing || isMutualFollowing }" @click="toggleFollow">
					{{ getMutualFollowText() }}
				</wd-button>
			</view>
		</view>

		<!-- 统计区块 -->
		<view class="count-wrap">
			<view class="count-item">
				<view class="num">{{ userInfo?.follow_count || 0 }}</view>
				<view class="desc">关注</view>
			</view>
			<view class="count-item">
				<view class="num">{{ userInfo?.fans_count || 0 }}</view>
				<view class="desc">粉丝</view>
			</view>
			<view class="count-item">
				<view class="num">{{ userInfo?.post_count || 0 }}</view>
				<view class="desc">帖子</view>
			</view>
		</view>

		<!-- 主要内容块 -->
		<view class="content-wrap">
			<!-- tabs -->
			<wd-tabs v-model="tabIndex" slidable="always" @change="handleTabChange" auto-line-width animated swipeable>
				<block v-for="(item, index) in tabList" :key="item">
					<wd-tab :title="item.title">
						<view class="content">
							<q-post-list v-if="index === 0" :postList="item.postList" :loadStatus="loadStatus"></q-post-list>
							<q-post-list v-else-if="index === 1" :postList="item.postList" :loadStatus="loadStatus"></q-post-list>
							<q-post-list v-else-if="index === 2" :postList="item.postList" :loadStatus="loadStatus"></q-post-list>
						</view>
					</wd-tab>
				</block>
			</wd-tabs>
		</view>
	</view>
</template>

<script setup>
import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { baseAPI } from '@/api/index.js';
import { useUserStore } from '@/store/user.js';
import utils from '@/utils/utils.js';

const userStore = useUserStore();

const userInfo = ref(null);
const loadStatus = ref('loading');
const isFollowing = ref(false);
const isMutualFollowing = ref(false);
const currentUserId = ref(null);
const tabIndex = ref(0);

const tabList = ref([
	{
		title: '动态',
		page: 1,
		postList: []
	},
	{
		title: '点赞',
		page: 1,
		postList: []
	},
	{
		title: '收藏',
		page: 1,
		postList: []
	}
]);

onLoad((options) => {
	if (options.id) {
		currentUserId.value = options.id;
		getUserInfo();
		if (userStore.userInfo && userStore.userInfo.id !== parseInt(options.id)) {
			checkFollowStatus();
		}
		// 默认加载动态
		getPostsByUserId();
	} else {
		// 如果没有传递id参数，显示错误提示
		uni.showToast({
			title: '用户ID参数缺失',
			icon: 'none'
		});
		setTimeout(() => {
			uni.navigateBack();
		}, 1500);
	}
});

onShow(() => {
	// 页面显示时刷新关注状态
	if (currentUserId.value && userStore.userInfo && userStore.userInfo.id !== parseInt(currentUserId.value)) {
		checkFollowStatus();
	}
});

onReachBottom(() => {
	// 移除原有的onReachBottom逻辑，因为现在使用tabs
});

// 获取用户信息
function getUserInfo() {
	baseAPI
		.get('/user/getUserById', {
			user_id: currentUserId.value
		})
		.then((res) => {
			if (res.code === 200) {
				userInfo.value = res.result;
			} else {
				uni.showToast({
					title: res.message || '获取用户信息失败',
					icon: 'none'
				});
			}
		})
		.catch((error) => {
			console.error('获取用户信息失败:', error);
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none'
			});
		});
}

// 页面公共函数
function handleTabChange({ index }) {
	tabIndex.value = index;

	const length = tabList.value[index].postList.length;

	if (index === 0 && length === 0) {
		getPostsByUserId();
	}

	if (index === 1 && length === 0) {
		getLikesByUserId();
	}

	if (index === 2 && length === 0) {
		getFavoritesByUserId();
	}
}

function getPostsByUserId() {
	loadStatus.value = 'loading';
	baseAPI
		.post('post/getListByPage', {
			page: tabList.value[0].page,
			queryForm: {
				user_id: currentUserId.value
			}
		})
		.then((res) => {
			if (res.code == 200) {
				tabList.value[0].postList.push(...res.result.list);
			}
			loadStatus.value = 'finished';
		});
}

function getFavoritesByUserId() {
	loadStatus.value = 'loading';
	// 调用新的后端接口，通过用户ID获取收藏列表
	baseAPI
		.get('post/favoritesByUserId', {
			user_id: currentUserId.value
		})
		.then((res) => {
			if (res.code == 200) {
				tabList.value[2].postList.push(...res.result.list);
			}
			loadStatus.value = 'finished';
		})
		.catch((error) => {
			console.error('获取收藏列表失败:', error);
			loadStatus.value = 'finished';
		});
}

function getLikesByUserId() {
	loadStatus.value = 'loading';
	// 调用新的后端接口，通过用户ID获取点赞列表
	baseAPI
		.get('post/likesByUserId', {
			user_id: currentUserId.value
		})
		.then((res) => {
			if (res.code == 200) {
				tabList.value[1].postList.push(...res.result.list);
			}
			loadStatus.value = 'finished';
		})
		.catch((error) => {
			console.error('获取点赞列表失败:', error);
			loadStatus.value = 'finished';
		});
}

// 检查关注状态
function checkFollowStatus() {
	baseAPI
		.get('user/checkFollowStatus', {
			follow_user_id: currentUserId.value
		})
		.then((res) => {
			if (res.code === 200) {
				isFollowing.value = res.result.is_following;
				isMutualFollowing.value = res.result.is_mutual_following;
			}
		})
		.catch((error) => {
			console.error('检查关注状态失败:', error);
		});
}

// 关注/取消关注
function toggleFollow() {
	if (!userStore.userInfo) {
		uni.navigateTo({
			url: '/pages/login/index'
		});
		return;
	}

	const action = isFollowing.value ? 'unfollow' : 'follow';
	baseAPI
		.post(`user/${action}`, {
			follow_user_id: currentUserId.value
		})
		.then((res) => {
			if (res.code === 200) {
				// 重新检查关注状态
				checkFollowStatus();
				// 重新获取用户信息以更新粉丝数
				getUserInfo();

				uni.showToast({
					title: isFollowing.value ? '关注成功' : '取消关注成功',
					icon: 'success'
				});
			} else {
				uni.showToast({
					title: res.message || '操作失败',
					icon: 'none'
				});
			}
		})
		.catch((error) => {
			console.error('关注操作失败:', error);
			uni.showToast({
				title: '操作失败',
				icon: 'none'
			});
		});
}

// 获取关注按钮文本
function getMutualFollowText() {
	if (isMutualFollowing.value) {
		return '互相关注';
	} else if (isFollowing.value) {
		return '已关注';
	} else {
		return '关注';
	}
}

function onBack() {
	uni.navigateBack();
}
</script>

<style lang="scss" scoped>
.head-bg {
	width: 100%;
	height: 500rpx;
	position: absolute;
	background-image: linear-gradient(rgba($-color-theme, 0.5), #f5f5f5);
	z-index: 1;
}

.page-content {
	position: relative;
	z-index: 10;
	padding-top: calc(var(--status-bar-height) + 120rpx);
}

.user-info {
	padding: $base-spacing;
	display: flex;
	align-items: center;

	.avatar {
		border-radius: 60rpx;
	}

	.right-wrap {
		flex: 1;
		margin-left: 20rpx;

		.nickname {
			font-weight: 600;
			margin-bottom: 5rpx;
		}

		.id {
			font-size: 20rpx;
			color: #616161;
		}

		.intro {
			margin-top: 8rpx;
			font-size: 24rpx;
			color: #616161;
			line-height: 1.4;
			word-break: break-word;
		}
	}
}

.follow-btn-wrap {
	margin-left: 20rpx;
}

.followed {
	background-color: #f0f0f0 !important;
	color: #666 !important;
}

.count-wrap {
	margin-top: 100rpx;
	display: flex;
	align-items: center;
	// background-color: #fff;
	border-radius: $base-radius;
	padding: $base-spacing;
	margin: $base-spacing;

	.count-item {
		flex: 1;
		text-align: center;

		.num {
			font-weight: 600;
		}

		.desc {
			font-size: 24rpx;
			color: #616161;
		}
	}
}

.content-wrap {
	border-radius: 30rpx 30rpx 0 0;
	overflow: hidden;

	.content {
		min-height: 60vh;
		padding: 20rpx;
		background-color: #f5f5f5;
	}
}
</style>
